
#include "ControlWin32.hpp"

namespace Gui
{
    std::map<HWND, ControlWin32*> ControlWin32::s_mapControls;
    
        
    void ControlWin32::AddControl (HWND hWnd, ControlWin32* Ctrl)
    {
        std::map<HWND, ControlWin32*>::iterator it;
        
        it = ControlWin32::s_mapControls.find(hWnd);
        
        if (it == ControlWin32::s_mapControls.end())
            ControlWin32::s_mapControls[hWnd] = Ctrl;
        
    }
    
    
    ControlWin32* ControlWin32::GetControl (HWND hWnd)
    {
        std::map<HWND, ControlWin32*>::iterator it;
        
        it = ControlWin32::s_mapControls.find(hWnd);
        
        if (it != ControlWin32::s_mapControls.end())
            return it->second;
        else
            return NULL;
    }
    
    
    void ControlWin32::RemoveControl (HWND hWnd)
    {
        std::map<HWND, ControlWin32*>::iterator it;
        
        it = ControlWin32::s_mapControls.find(hWnd);
        
        if (it != ControlWin32::s_mapControls.end())
            ControlWin32::s_mapControls.erase(it);
    }
    
    
    ControlWin32::ControlWin32() : m_hWnd(NULL)
    {
    }
    
    
    ControlWin32::~ControlWin32()
    {
        if (m_hWnd)
        {
            ControlWin32::RemoveControl(m_hWnd);
            DestroyWindow(m_hWnd);
            m_hWnd = NULL;
        }
    }
    
    
	void ControlWin32::PropertySet_Text( const std::string &Value)
	{
		SetWindowText(m_hWnd, Value.c_str());
	}


	std::string ControlWin32::PropertyGet_Text()
	{
		std::string Text;
		
		Text.reserve(GetWindowTextLength(m_hWnd));
		GetWindowText(m_hWnd, const_cast<CHAR*>(Text.c_str()), Text.size() + 1);

		return Text;
	}


	void ControlWin32::PropertySet_Visible( const bool &Value )
	{
		if (Value)
			ShowWindow(m_hWnd, TRUE);
		else
			ShowWindow(m_hWnd, FALSE);
	}


	bool ControlWin32::PropertyGet_Visible()
	{
        //TODO
		return false;
	}


	void ControlWin32::PropertySet_Position( const Vector2<int>& Value )
	{
		RECT WndRect;

		GetWindowRect(m_hWnd, &WndRect);
		SetWindowPos(	m_hWnd, NULL,
						Value.X ,
						Value.Y,
						WndRect.right - WndRect.left,
						WndRect.bottom - WndRect.top, 0);
	}


	void ControlWin32::PropertySet_Size( const Size2<int>& Value )
	{
		RECT WndRect;

		GetWindowRect(m_hWnd, &WndRect);
		SetWindowPos(	m_hWnd, NULL,
						WndRect.left ,
						WndRect.top,
						Value.Width,
						Value.Height, 0);
	}


	Vector2<int> ControlWin32::PropertyGet_Position()
	{
		RECT WndRect;

		GetWindowRect(m_hWnd, &WndRect);

		return Vector2<int>( WndRect.left, WndRect.top );
	}


	Size2<int> ControlWin32::PropertyGet_Size()
	{
		RECT WndRect;

		GetWindowRect(m_hWnd, &WndRect);

		return Size2<int>( WndRect.right - WndRect.left, WndRect.bottom - WndRect.top );
	}
	
	
	HWND ControlWin32::GetHWND() const
	{
	    return m_hWnd;
	}
}
